const API_BASE_URL = '/'
const ERROR_MSG = '系统繁忙，请稍后重试'

/* http request
* @url api地址
* @params 参数
* @method 方法
* @showToast 显示toast
* */
function request (url, params = null, method, showToast) {
    url = getUrl(method, url)

    const header = {
        token: getToken()
    }

    return new Promise((resolve, reject) => {
        wx.request({
            url,
            header,
            data: params,
            method,
            success ({ statusCode, data: res }) {
                if (statusCode === 500) {
                    toast(showToast, ERROR_MSG)
                    reject(new Error(ERROR_MSG))
                    return
                }

                try {
                    const { code, data, msg } = res

                    switch (code) {
                        case 0:
                            resolve(data)
                            break
                        case 401: // 无权限
                            tokenInvalidHandle()
                            reject(new Error(msg))
                            break
                        default:
                            reject(res)

                            if (code) {
                                toast(showToast, code >= 500 ? ERROR_MSG : msg)
                            } else {
                                console.info('数据格式错误', res)
                                toast(showToast, ERROR_MSG)
                            }

                            break
                    }
                } catch (e) {
                    console.info('数据格式错误', res)
                    console.error(e)
                    toast(showToast, ERROR_MSG)
                    reject(new Error(ERROR_MSG))
                }
            },
            fail (err) {
                console.log('request:fail')
                console.error(err)

                let { errMsg, statusCode } = err
                if (errMsg.includes('request:fail')) {
                    wx.getNetworkType({
                        success ({networkType}) {
                            if (networkType === 'none') {
                                toast(showToast, '网络断开，请检查设置')
                            } else {
                                toast(showToast, ERROR_MSG)
                            }
                        },
                        fail () {
                            toast(showToast, ERROR_MSG)
                        }
                    })
                } else {
                    toast(showToast, statusCode >= 500 ? ERROR_MSG : errMsg)
                }
                reject(err)
            }
        })
    })
}

/* http upload
* @url 上传地址
* @path 文件临时路径
* @progressCallback 上传进度回调函数
* @showToast 显示toast
* */
function upload (url, path, formData, progressCallback, showToast) {
    url = getUrl('POST', url)
    const token = getToken()
    return new Promise((resolve, reject) => {
        const uploadTask = wx.uploadFile({
            url,
            header: {token},
            name: 'file',
            filePath: path,
            formData,
            success (res) {
                try {
                    if (typeof res.data === 'string') {
                        res = JSON.parse(res.data)
                    }
                } catch (err) {
                    reject(err)
                }
                if (res.code === 0) {
                    resolve(res.data)
                } else if (res.code === 401) {
                    tokenInvalidHandle()
                    reject(new Error(res.msg))
                } else {
                    reject(new Error(res.msg))
                    toast(showToast, res.msg)
                }
            },
            fail (err) {
                console.log(err)
                reject(err)
            }
        })
        // 上传进度
        uploadTask.onProgressUpdate(res => {
            if (typeof progressCallback === 'function') {
                progressCallback(res, path)
            }
        })
    })
}

function getUrl (method, url) {
    return API_BASE_URL + url
}

function getToken () {
    // todo: 获取 token
    return ''
}

function toast (showToast, title) {
    if (showToast && title) {
        setTimeout(() => {
            wx.showToast({
                title,
                icon: 'none',
                duration: 2000
            })
        }, 0) // 定时器 避免 loading 警告
    }
}

// token 失效处理
function tokenInvalidHandle () {
    toast(true, '登录已过期，请重新登录')
    // todo 清空登录信息
    wx.reLaunch({
        url: '/pages/login'
    })
}

export default {
    get (url, params, showToast = true) {
        return request(url, params, 'GET', showToast)
    },
    post (url, params, showToast = true) {
        return request(url, params, 'POST', showToast)
    },
    put (url, params, showToast = true) {
        return request(url, params, 'PUT', showToast)
    },
    del (url, params, showToast = true) {
        return request(url, params, 'DELETE', showToast)
    },
    upload (url, params, progressCallback, showToast = true) {
        return upload(url, params, progressCallback, showToast)
    }
}
